package com.alm.token.ui.activity;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupMenu;
import android.widget.TextView;

import com.alm.token.ConStant;
import com.alm.token.MyApp;
import com.alm.token.R;
import com.alm.token.base.BaseActivity;
import com.alm.token.ui.data.bean.AddDrawData;
import com.alm.token.ui.data.bean.DrawIndexData;
import com.alm.token.ui.data.bean.RegisterData;
import com.alm.token.ui.data.bean.TransferTransData;
import com.alm.token.ui.data.bean.TurnOutBiTB_QRdata;
import com.alm.token.ui.persenter.MyPreenter;
import com.alm.token.ui.view.TurmOutView;
import com.alm.token.utils.ActionBarHelper;
import com.alm.token.utils.CommonUtil;
import com.alm.token.utils.EmptyUtils;
import com.alm.token.utils.LanguageUtils;
import com.alm.token.utils.LogUtil;
import com.google.gson.Gson;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.yzq.zxinglibrary.encode.CodeCreator;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

import static com.alm.token.ui.activity.FundArealistActivity.INTENT_RESULT_CODE_VAULE;
import static com.alm.token.ui.activity.FundArealistActivity.INTENT_RESULT_SUCC_CODE;

//import com.uuzuche.lib_zxing.activity.CaptureActivity;
//import com.uuzuche.lib_zxing.activity.CodeUtils;
//import com.uuzuche.lib_zxing.activity.ZXingLibrary;

public class TurnOutBiTB_ShoukuanActivity extends BaseActivity implements TurmOutView<Object> {

    @BindView(R.id.ly_savebody)
    LinearLayout lySaveBody;

    @BindView(R.id.img_adressqrcode)
    ImageView imgAdressqrcode;
    @BindView(R.id.tv_setmoneynumber)
    TextView tvSetmoneynumber;
    @BindView(R.id.tv_setmoneytype)
    TextView tvSetmoneytype;
    @BindView(R.id.ly_bodylongclick)
    LinearLayout lyBodylongclick;
    @BindView(R.id.tv_moneynumbershow)
    TextView tvMoneynumbershow;
    @BindView(R.id.tv_moneytypeshow)
    TextView tvMoneytypeshow;

    @BindView(R.id.tv_username)
    TextView tvUsername;
    @BindView(R.id.tv_moneynumbershow1)
    TextView tvMoneynumbershow1;
    @BindView(R.id.tv_moneytypeshow1)
    TextView tvMoneytypeshow1;
    @BindView(R.id.img_adressqrcode1)
    ImageView imgAdressqrcode1;
    @BindView(R.id.tv_paytype)
    TextView tvPaytype;


    private DrawIndexData.DataBean drawIndexDataBean;
    List<DrawIndexData.DataBean.WalletsBean> walletsBeans = new ArrayList<>();
    private Bitmap qrCodeBitmap = null;
    private Bitmap bodyBitmap = null;

    private String result = "";
    private int indext = -1;
    private double money = 0.00d;

    private TurnOutBiTB_QRdata turnOutBiTB_qRdata;

    @Override
    protected MyPreenter initPreenter() {
        return new MyPreenter(this);
    }

    @Override
    protected int getContentViewId() {
        return R.layout.activity_turnout_shoukuan;
    }

    @Override
    protected void initVariables() {
//        result = getIntent().getStringExtra("scanResult");
//        if (EmptyUtils.isNotEmpty(result) && result.indexOf("CollectionPayment") != -1) {
//            turnOutBiTB_qRdata = new Gson().fromJson(result, TurnOutBiTB_QRdata.class);
//        }
        turnOutBiTB_qRdata = new TurnOutBiTB_QRdata();
        if (EmptyUtils.isEmpty(MyApp.getUserData()) || EmptyUtils.isEmpty(MyApp.getUserData().getData()) || EmptyUtils.isEmpty(MyApp.getUserData().getData().getUser())) {
            turnOutBiTB_qRdata.setAddress("");
        }else {
            turnOutBiTB_qRdata.setAddress(MyApp.getUserData().getData().getUser().getLoginname());
        }
        turnOutBiTB_qRdata.setType("CollectionPayment");
        turnOutBiTB_qRdata.setCoinName("");
        turnOutBiTB_qRdata.setCoinId("");
        turnOutBiTB_qRdata.setPrice("");
        result = new Gson().toJson(turnOutBiTB_qRdata);//把对象转为JSON格式的字符串
        LogUtil.e(result);

        if (EmptyUtils.isEmpty(MyApp.getUserData()) || EmptyUtils.isEmpty(MyApp.getUserData().getData()) || EmptyUtils.isEmpty(MyApp.getUserData().getData().getUser())) {
            tvUsername.setText("");
        }else {
            tvUsername.setText(MyApp.getUserData().getData().getUser().getLoginname());
        }

        tvMoneynumbershow1.setText(EmptyUtils.returnNOTNull(turnOutBiTB_qRdata.getPrice()));
        tvMoneytypeshow1.setText(EmptyUtils.returnNOTNull(turnOutBiTB_qRdata.getCoinName()));
        if (EmptyUtils.isNotEmpty(turnOutBiTB_qRdata.getCoinName())) {
            tvPaytype.setText(getString(R.string.tv_hint_onleypay, turnOutBiTB_qRdata.getCoinName()));
        } else {
            tvPaytype.setText(getString(R.string.tv_hint_morepay));
        }

        initAddressQRCode();
    }

    @Override
    protected void initViews() {
//        new ActionBarHelper(this).setTitle(getString(R.string.app_hint_superegg));
        new ActionBarHelper(this).setTitle(getString(R.string.tv_hint_qdshoukuan));
        lyBodylongclick.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                if (LanguageUtils.getSetIndex() == 1) {
                    lySaveBody.setBackground(getResources().getDrawable(R.drawable.icon_save_bg1));
                } else if (LanguageUtils.getSetIndex() == 3){
                    lySaveBody.setBackground(getResources().getDrawable(R.drawable.icon_save_bg3));
                }else if (LanguageUtils.getSetIndex() == 4){
                    lySaveBody.setBackground(getResources().getDrawable(R.drawable.icon_save_bg4));
                }else {
                    lySaveBody.setBackground(getResources().getDrawable(R.drawable.icon_save_bg2));
                }

                bodyBitmap = CommonUtil.getBitMapFromView(lySaveBody);

                if (bodyBitmap == null) {
                    showToast(getString(R.string.network_loading_hint1));
                    return false;
                }
                //存储权限
                RxPermissions rxPermissions = new RxPermissions(TurnOutBiTB_ShoukuanActivity.this);
                rxPermissions.request(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                        .subscribe(new Observer<Boolean>() {
                            @Override
                            public void onSubscribe(Disposable d) {
                            }

                            @Override
                            public void onNext(Boolean granted) {
                                if (granted) {
                                    if (saveImageToGallery(TurnOutBiTB_ShoukuanActivity.this, bodyBitmap, getString(R.string.tv_hint_shoufukuanqd) + CommonUtil.getStringDate() + ".jpg")) {
                                        showToast(getString(R.string.profile_hint_item15));
                                    }
                                }
                            }

                            @Override
                            public void onError(Throwable e) {
                            }

                            @Override
                            public void onComplete() {
                            }
                        });
                return false;
            }
        });
    }

    private void initAddressQRCode() {

//        layoutView(lyQrcodeBody,CommonUtil.px2dip(this,470),CommonUtil.px2dip(this,600));

        qrCodeBitmap = CodeCreator.createQRCode(result,
                CommonUtil.dip2px(this, 200),
                CommonUtil.dip2px(this, 200),
                BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher));
        imgAdressqrcode.setImageBitmap(qrCodeBitmap);
        imgAdressqrcode1.setImageBitmap(qrCodeBitmap);

    }

    @Override
    protected void loadData() {
        preenter.getTransferIndexData();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
//            case R.id.ly_ooutmoneybizhongtop:
//                showPopupMenu2(lyOoutmoneybizhongtop);
//                break;
//            case R.id.tv_outmoneycommit:
//                break;
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    public void mathNumber(double number) {


//        LogUtil.e("leatNumber1=" + leatNumber);
//        BigDecimal b = new BigDecimal(leatNumber);
//        leatNumber = b.setScale(4, BigDecimal.ROUND_UP).doubleValue();
//        LogUtil.e("leatNumber2=" + leatNumber);
//        dec1 = new DecimalFormat("0.0000");
//        tvEdtleastNumber.setText(getString(R.string.currency_hint1_leastinput, CommonUtil.saveToPoint4WithNo(leatNumber)));
//        money = number * walletsBeans.get(bizhongselect).getPrice();
//        dec1 = new DecimalFormat("0.00");

    }

    public void showPopupMenu2(View view) {
        //参数View 是设置当前菜单显示的相对于View组件位置，具体位置系统会处理
        PopupMenu popupMenu = new PopupMenu(this, view);
        //加载menu布局
        Menu menu = popupMenu.getMenu();
        for (DrawIndexData.DataBean.WalletsBean walletsBean : walletsBeans) {
            menu.add(walletsBean.getName());
        }
        popupMenu.getMenuInflater().inflate(R.menu.menu_popmenu, menu);


        //设置menu中的item点击事件
        popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {

                for (int i = 0; i < walletsBeans.size(); i++) {
                    if (item.getTitle().toString().equalsIgnoreCase(walletsBeans.get(i).getName())) {

                        if (EmptyUtils.isNotEmpty(turnOutBiTB_qRdata)) {
                            turnOutBiTB_qRdata.setCoinId(walletsBeans.get(i).getId() == 0 ? "" : walletsBeans.get(i).getId() + "");
                            turnOutBiTB_qRdata.setCoinName(walletsBeans.get(i).getName().equalsIgnoreCase(getString(R.string.tv_hint_selectpaytype)) ? "" : walletsBeans.get(i).getName());
                            String moneytype = EmptyUtils.isNotEmpty(turnOutBiTB_qRdata.getCoinName()) ? "(" + turnOutBiTB_qRdata.getCoinName() + ")" : "";
                            tvSetmoneytype.setText(getString(R.string.tv_hint_paytype) + moneytype);
                            tvMoneytypeshow.setText(turnOutBiTB_qRdata.getCoinName());
                        }
                        result = new Gson().toJson(turnOutBiTB_qRdata);//把对象转为JSON格式的字符串
                        LogUtil.e(result);

                        if (EmptyUtils.isEmpty(MyApp.getUserData()) || EmptyUtils.isEmpty(MyApp.getUserData().getData()) || EmptyUtils.isEmpty(MyApp.getUserData().getData().getUser())) {
                            tvUsername.setText("");
                        }else {
                            tvUsername.setText(MyApp.getUserData().getData().getUser().getLoginname());
                        }
                        tvMoneynumbershow1.setText(turnOutBiTB_qRdata.getPrice());
                        tvMoneytypeshow1.setText(turnOutBiTB_qRdata.getCoinName());
                        if (EmptyUtils.isNotEmpty(turnOutBiTB_qRdata.getCoinName())) {
                            tvPaytype.setText(getString(R.string.tv_hint_onleypay, turnOutBiTB_qRdata.getCoinName()));
                        } else {
                            tvPaytype.setText(getString(R.string.tv_hint_morepay));
                        }

                        initAddressQRCode();
                        break;
                    }
                }
                return true;
            }
        });
        popupMenu.show();
    }

    @Override
    public void getData(Object o) {

    }

    @Override
    public void jumpToLoginAct(int staue) {
        if (staue == 3) {
//            showToast(getString(R.string.common_relogin));
//            Intent intent = new Intent();
//            intent.setAction(ConStant.EXIT_APP);
//            sendBroadcast(intent);
//            startActivity(BlockWalletLoginActivity.class);
//            finish();
        } else if (staue == 4) {
//            showToast(getString(R.string.paypasw_hint_setpaypsw));
//            Intent intent = new Intent(getActivity(),PayPwdActivity.class);
//            intent.putExtra("PayPwdActivityType",PayPwdActivity.PAYPSW_SET);
//            startActivity(intent);
//            getActivity().finish();
            showToSetPaypswDialog();
        } else if (staue == 666) {
            showToUpdata();
        }
    }

    @Override
    public void onError(String error) {
        showToast(error);
    }

    @Override
    public void ShowProgress() {
        showWaitDialog();
    }

    @Override
    public void hideProgress() {
        hideWaitDialog();
    }

    @Override
    public void getDrawIndexData(DrawIndexData drawIndexData) {

    }

    @Override
    public void getAddDrawData(AddDrawData addDrawData) {

    }

    @Override
    public void getCode(RegisterData registerData) {

    }

    @Override
    public void getTransferIndexData(DrawIndexData drawIndexData) {
        if (drawIndexData.getStatus() == 0) {
            drawIndexDataBean = drawIndexData.getData();
            if (drawIndexDataBean != null) {
                walletsBeans.clear();
                DrawIndexData.DataBean.WalletsBean walletsBean = new DrawIndexData.DataBean.WalletsBean();
                walletsBean.setName(getString(R.string.tv_hint_selectpaytype));
                walletsBeans.add(walletsBean);
                if(EmptyUtils.isNotEmpty(drawIndexDataBean.getWallet())){
                    walletsBeans.addAll(drawIndexDataBean.getWallet());
                }
            } else {
                showToast(drawIndexData.getMsg());
            }
        } else {
            showToast(drawIndexData.getMsg());
        }
    }

    @Override
    public void getTransfertransData(TransferTransData transferTransData) {

    }


    @Override
    public void getcheckLoginNameData(RegisterData checkLoginNameData) {

    }

    private int requestCode = 1000;

    @OnClick({R.id.tv_setmoneynumber, R.id.tv_setmoneytype})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_setmoneynumber:
                Intent intent1 = new Intent(this, TurnOutBiTB_shoukuannumber_Activity.class);
                startActivityForResult(intent1, requestCode);
                break;
            case R.id.tv_setmoneytype:
                showPopupMenu2(tvSetmoneytype);
                break;

        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == requestCode && resultCode == INTENT_RESULT_SUCC_CODE && data != null) {

            String money = data.getStringExtra(INTENT_RESULT_CODE_VAULE);
            LogUtil.e("money=" + money);


            if (EmptyUtils.isNotEmpty(turnOutBiTB_qRdata)) {
                turnOutBiTB_qRdata.setPrice(EmptyUtils.isNotEmpty(money) && Double.valueOf(money) != 0 ? money : "");
                tvMoneynumbershow.setText(turnOutBiTB_qRdata.getPrice());
            }
            result = new Gson().toJson(turnOutBiTB_qRdata);//把对象转为JSON格式的字符串
            LogUtil.e(result);
            tvUsername.setText(MyApp.getUserData().getData().getUser().getLoginname());
            tvMoneynumbershow1.setText(turnOutBiTB_qRdata.getPrice());
            tvMoneytypeshow1.setText(turnOutBiTB_qRdata.getCoinName());

            if (EmptyUtils.isNotEmpty(turnOutBiTB_qRdata.getCoinName())) {
                tvPaytype.setText(getString(R.string.tv_hint_onleypay, turnOutBiTB_qRdata.getCoinName()));
            } else {
                tvPaytype.setText(getString(R.string.tv_hint_morepay));
            }
            initAddressQRCode();
        }
    }

    /**
     * 保存图片到指定路径
     *
     * @param context
     * @param bitmap   要保存的图片
     * @param fileName 自定义图片名称
     * @return
     */
    public static boolean saveImageToGallery(Context context, Bitmap bitmap, String fileName) {
        //系统相册目录
        String storePath = Environment.getExternalStorageDirectory()
                + File.separator + Environment.DIRECTORY_DCIM
                + File.separator + "Camera" + File.separator;

        // 保存图片至指定路径
//        String storePath = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "qrcode";


        File appDir = new File(storePath);
        if (!appDir.exists()) {
            appDir.mkdir();
        }
        File file = new File(appDir, fileName);
        try {
            FileOutputStream fos = new FileOutputStream(file);
            //通过io流的方式来压缩保存图片(80代表压缩20%)
            boolean isSuccess = bitmap.compress(Bitmap.CompressFormat.JPEG, 80, fos);
            fos.flush();
            fos.close();

            //发送广播通知系统图库刷新数据
            Uri uri = Uri.fromFile(file);
            context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri));
            if (isSuccess) {
                return true;
            } else {
                return false;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }
}
